$(function () {
    obj.init();
});

var obj = new function() {
    return {
        addAreaGroupForm: null,
        form: null,
        demo:null,
        subjectData: null,
        versionData: null,
        needChange: true,
        init: function () {
            this.demo = $('.SubVerTr').eq(0).clone();
            this.addAreaGroupForm = $('#addAreaGroup_form');
            this.form = new xhForm(this.addAreaGroupForm);
            if (groupId !== 0){
                this.funObj().addSubVersionData();//填充学科版本信息
            }
            this.listener();
        },
        listener: function () {
            var $this = this;
            // 学科改变
            $this.addAreaGroupForm.on('change','[id^="subject_"]',function () {
                var id = $(this).attr("id").split("subject_")[1];
                if ($this.needChange){
                    $this.funObj().changeSubject(id);
                }
            });
            // 版本改变
            $this.addAreaGroupForm.on('change','[id^="version_"]',function () {
                var id = $(this).attr("id").split("version_")[1];
                if ($this.needChange){
                    $this.funObj().changeVersion(id);
                }
            });
            //添加学科版本
            $('#add').click(function () {
                $this.funObj().addAction();
            });
            //删除学科版本
            $this.addAreaGroupForm.on('click','[id^="delLine_"]',function () {
                var id = $(this).attr("id").split("delLine_")[1];
                $this.funObj().removeSubVer(id);
            });
            //保存学科版本信息
            $('#save').click(function () {
                $this.funObj().saveAction();
            });
            //添加年级-组
            $this.addAreaGroupForm.on('click','[id^="addSingleGrade_"]',function () {
                var id = $(this).attr("id").split("addSingleGrade_")[1];
                $this.funObj().addSingleGrade(id);
            });
            //添加年级-白名单
            $this.addAreaGroupForm.on('click','[id^="addSingleGradeWhite_"]',function () {
                var id = $(this).attr("id").split("addSingleGradeWhite_")[1];
                $this.funObj().addSingleGradeWhite(id);
            });
            //删除年级
            $this.addAreaGroupForm.on('click','[id^="singleGradeA_"]',function () {
                var id = $(this).attr("id").split("singleGradeA_")[1];
                $this.funObj().delSingleGrade(id);
            });
        },
        funObj: function () {
            var $this = this;
            var form = this.addAreaGroupForm;
            return {
                addSubVersionData: function () {
                    // xhExtra.ajaxRequest('res/getSubVerData', {groupId: groupId}, {check:true}, function (data) {
                    xhExtra.ajaxRequest('res/getAllData', {groupId: groupId,schoolId: schoolId,stageId: stageId}, {check:true}, function (postData) {
                        var data = postData['data'];
                        var whiteArr = postData['white'];

                        // var blackArr = [];
                        // var whiteArr = [];
                        // xhExtra.ajaxRequest('res/getSchoolTextBook', {schoolId: schoolId,stageId: stageId}, {check:true,async: false}, function (res) {
                        //     blackArr = res.black;
                        //     whiteArr = res.white;
                        // });
                        $this.needChange = false;
                        $('#subject_0').select2({placeholder: '请选择学科'});
                        $('#version_0').select2({placeholder: '请选择版本'});

                        //填充区域组组内数据
                        if (data.empty_sub === 1){
                            $.each(data.data, function (index, value) {
                                if (index !== 0){//非第一行
                                    var dom = $($this.demo.clone());
                                    $('.SubVerTr:last').after(dom);
                                    dom.find('[name="data[0][subjectId]"]').attr('name','data['+index+'][subjectId]').attr('id','subject_'+index);
                                    dom.find('[name="data[0][versionId]"]').attr('name','data['+index+'][versionId]').attr('id','version_'+index);
                                    dom.find('[id="grade_0"]').attr('id','grade_'+index);
                                    dom.attr('id','trId_'+index);
                                }
                                var subObj = $('#subject_'+index).addClass('needDisable').prop('disabled',true);
                                subObj.select2({placeholder: '请选择学科', data: data.subject, allowClear: true});//学科列表
                                subObj.val(value.subVerData.sub).trigger("change");//学科数据

                                var verObj = $('#version_'+index).addClass('needDisable').prop('disabled',true);
                                verObj.select2({placeholder: '请选择版本', data: value.version, allowClear: true});//版本列表

                                if (value.empty_ver !== 1){//版本为空
                                    verObj.select2({placeholder: '请选择版本'});
                                } else {
                                    verObj.val(value.subVerData.ver).trigger("change");//版本数据
                                    if (value.empty_gra !== 1){//年级为空
                                        str = '<span style="color: grey;font-size:12px;">暂无年级数据</span>';
                                    } else {
                                        str = '';
                                        var length = 0;
                                        $.each(value.grade, function (id, name) {
                                            var exist = $.inArray(parseInt(id),value.subVerData.gra_data.data);//如果在群组中存在
                                            if (exist >= 0){
                                                str += '<label title="组内数据" style="width: fit-content;padding-right: 5px">' +
                                                    '<input type="checkbox" name="data['+index+'][grade][data][]" checked value="' + id + '">'+ name +
                                                    '</label>';
                                            }
                                            var existBlack = $.inArray(parseInt(id),value.subVerData.gra_data.black);//如果在黑名单中存在
                                            if(existBlack >= 0){
                                                str += '<label title="黑名单数据" style="width: fit-content;padding-right: 5px">' +
                                                    '<input type="checkbox" name="data['+index+'][grade][data][]" value="' + id + '">'+ name +
                                                    '</label>';
                                            } else {
                                                var existWhite = $.inArray(parseInt(id),value.subVerData.gra_data.white);//如果在白名单中存在
                                                if (existWhite >= 0){
                                                    str += '<label title="白名单数据" id="singleGradeLab_'+index+'_'+id+'s" style="width: fit-content;">' +
                                                        '<input type="checkbox" name="data['+index+'][grade][white][]" checked value="' + id + '">'+ name +
                                                        '</label>' +
                                                        '<a id="singleGradeA_'+index+'_'+id+'s" style="margin-right: 5px;cursor: pointer;color: red;padding-right: 5px">×</a>';
                                                }
                                            }
                                        });
                                        str += '<a id="addSingleGrade_'+index+'" style="margin-right: 5px;cursor: pointer;color: blue;">+添加年级</a>';
                                    }
                                    form.find('#grade_'+index).append($(str));
                                }
                            });
                        }

                        //填充白名单数据
                        if (JSON.stringify(whiteArr) !== '[]'){
                            $.each(whiteArr.data, function (index_key, value) {
                                var dom = $($this.demo.clone());
                                $('.SubVerTr:last').after(dom);
                                var index = $('.SubVerTr').length - 1 ;
                                dom.find('[name="data[0][subjectId]"]').attr('name','white['+index+'][subjectId]').attr('id','subject_'+index);
                                dom.find('[name="data[0][versionId]"]').attr('name','white['+index+'][versionId]').attr('id','version_'+index);
                                dom.find('[id="grade_0"]').attr('id','grade_'+index);
                                dom.find('[id="delTdLine_0"]').attr('id','delTdLine_'+index);
                                dom.find('[id="delLine_0"]').attr('id','delLine_'+index);
                                dom.attr('id','trId_'+index);
                                document.getElementById('delTdLine_'+index).style.display = 'table-cell';

                                var subObj = $('#subject_'+index);
                                subObj.select2({placeholder: '请选择学科', data: whiteArr.subject, allowClear: true});//学科列表
                                subObj.val(value.subVerData.sub).trigger("change");//学科数据

                                var verObj = $('#version_'+index);
                                if (value.empty_ver !== 1){//版本为空
                                    verObj.select2({placeholder: '请选择版本'});
                                } else {
                                    verObj.select2({placeholder: '请选择版本', data: value.version, allowClear: true});//版本列表
                                    verObj.val(value.subVerData.ver).trigger("change");//版本数据
                                    if (value.empty_gra !== 1){//年级为空
                                        str = '<span style="color: grey;font-size:12px;">暂无年级数据</span>';
                                    } else {
                                        str = '';
                                        $.each(value.grade, function (id, name) {
                                            var exist = $.inArray(parseInt(id),value.subVerData.gra);//如果在白名单中
                                            if(exist >= 0){
                                                str += '<label title="白名单数据" id="singleGradeLab_'+index+'_'+id+'s" style="width: fit-content;">' +
                                                    '<input type="checkbox" name="white['+index+'][grade][]" checked value="' + id + '">'+ name +
                                                    '</label>';
                                                str += '<a id="singleGradeA_'+index+'_'+id+'s" style="margin-right: 5px;cursor: pointer;color: red;padding-right: 5px">×</a>';
                                            } else {
                                                var existBlack = $.inArray(parseInt(id),value.subVerData.black);//如果在黑名单中存在
                                                if(existBlack >= 0){
                                                    str += '<label title="黑名单数据" id="singleGradeLab_'+index+'_'+id+'s" style="width: fit-content;padding-right: 5px">' +
                                                        '<input type="checkbox" name="white['+index+'][grade][]" value="' + id + '">'+ name +
                                                        '</label>';
                                                    str += '<a id="singleGradeA_'+index+'_'+id+'s" style="margin-right: 5px;cursor: pointer;color: red;padding-right: 5px">×</a>';
                                                }
                                            }
                                        });
                                        str += '<a id="addSingleGradeWhite_'+index+'" style="margin-right: 5px;cursor: pointer;color: blue;">+添加年级</a>';
                                    }
                                    form.find('#grade_'+index).append($(str));
                                }
                            });
                        }
                        $this.needChange = true;
                    });
                },
                addSingleGrade: function (id) {
                    var sub = $('#subject_'+id).val();
                    var ver = $('#version_'+id).val();
                    var grade = [];
                    $this.addAreaGroupForm.find('[name^="data['+id+'][grade][data][]"]').each(function () {
                        grade.push($(this).val());
                    });
                    $this.addAreaGroupForm.find('[name^="data['+id+'][grade][white][]"]').each(function () {
                        grade.push($(this).val());
                    });
                    var length = grade.length;
                    window.top.xhTop.showModal({
                        title: '添加年级',
                        content: xhTool.getFrameString('res/setGradePage', {stage: stageId,sub:sub,ver:ver,grade:grade,id:id,lengthData:length,type:1,groupId:groupId}, 250),
                        button: '确定',
                        size: 'sm',
                        width:'600'
                    });
                },
                addGradeData: function (value, name, id, length, type, groupId, subject, version) {
                    if (type === 1){//组
                        // xhExtra.ajaxRequest('res/checkGradeInGroup', {groupId: groupId, subject: subject, version:version, grade:value}, {check:true}, function (data) {
                        //     if (data.isInGroup === 0){//检查添加项是否在群组中，不在
                        //         insertStr = '<input type="checkbox" name="data['+id+'][grade][white][]" checked value="';
                        //         removeStr = '<a id="singleGradeA_'+id+'_'+length+'" style="margin-right: 5px;cursor: pointer;color: red;padding-right: 5px">×</a>';
                        //     } else {//在
                        //         insertStr = '<input type="checkbox" name="data['+id+'][grade][data][]" checked value="';
                        //         removeStr = '<a id="singleGradeA_'+id+'_'+length+'" style="margin-right: 5px;cursor: pointer;color: red;padding-right: 5px">×</a>';
                        //         // removeStr = '';
                        //     }
                        //     str = '<label id="singleGradeLab_'+id+'_'+length+'" style="width: fit-content;">' +
                        //          insertStr + value + '">'+ name +
                        //         '</label>' +
                        //         removeStr +
                        //         '<a id="addSingleGrade_'+id+'" style="margin-right: 5px;margin-left: 5px;cursor: pointer;color: blue;">+添加年级</a>';
                        //     form.find('#grade_'+id).find('#addSingleGrade_'+id).remove();
                        //     form.find('#grade_'+id).append($(str));
                        // });
                        insertStr = '<input type="checkbox" name="data['+id+'][grade][white][]" checked value="';
                        removeStr = '<a id="singleGradeA_'+id+'_'+length+'" style="margin-right: 5px;cursor: pointer;color: red;padding-right: 5px">×</a>';
                        str = '<label id="singleGradeLab_'+id+'_'+length+'" style="width: fit-content;">' +
                            insertStr + value + '">'+ name +
                            '</label>' +
                            removeStr +
                            '<a id="addSingleGrade_'+id+'" style="margin-right: 5px;margin-left: 5px;cursor: pointer;color: blue;">+添加年级</a>';
                        form.find('#grade_'+id).find('#addSingleGrade_'+id).remove();
                        form.find('#grade_'+id).append($(str));
                    } else if (type === 2){//白名单
                        str = '<label id="singleGradeLab_'+id+'_'+length+'" style="width: fit-content;">' +
                            '<input type="checkbox" name="white['+id+'][grade][]" checked value="' + value + '">'+ name +
                            '</label>' +
                            '<a id="singleGradeA_'+id+'_'+length+'" style="margin-right: 5px;cursor: pointer;color: red;padding-right: 5px">×</a>' +
                            '<a id="addSingleGradeWhite_'+id+'" style="margin-right: 5px;cursor: pointer;color: blue;">+添加年级</a>';
                        form.find('#grade_'+id).find('#addSingleGradeWhite_'+id).remove();
                        form.find('#grade_'+id).append($(str));
                    }
                },
                addSingleGradeWhite: function (id) {
                    var sub = $('#subject_'+id).val();
                    var ver = $('#version_'+id).val();
                    var grade = [];
                    $this.addAreaGroupForm.find('[name^="white['+id+'][grade][]"]').each(function () {
                        grade.push($(this).val());
                    });
                    var length = grade.length;
                    // console.log(sub,ver,grade,id,length);return false;
                    window.top.xhTop.showModal({
                        title: '添加年级',
                        content: xhTool.getFrameString('res/setGradePage', {stage: stageId,sub:sub,ver:ver,grade:grade,id:id,lengthData:length,type:2,groupId:groupId}, 250),
                        button: '确定',
                        size: 'sm',
                        width:'600'
                    });
                },
                delSingleGrade: function (idStr) {
                    form.find('#singleGradeLab_'+idStr).remove();
                    form.find('#singleGradeA_'+idStr).remove();
                },
                removeSubVer: function (id) {
                    form.find('[id=trId_'+id+']').remove();
                },
                changeSubject: function (id) {
                    var subject = form.find('#subject_'+id).val();
                    var exist = $this.funObj().getExistDataArr(subject);
                    xhExtra.ajaxRequest('res/getVersionBySub', {stage: stageId, subject: subject}, {check:true}, function (data) {
                        var obj = $('#version_'+id);
                        obj.find("option").remove();
                        obj.select2({placeholder: '请选择版本', data: data, allowClear: true});
                        if (JSON.stringify(exist) !== '[]'){
                            exist.forEach(function(value,index){
                                form.find("#version_"+id+" option[value="+value+"]").prop('disabled',true);
                            });
                            obj.select2({placeholder: '请选择版本'});
                        }
                    });
                    form.find('#grade_'+id).html('');
                },
                getExistDataArr: function (subj_data) {
                    var arr = [];
                    $this.addAreaGroupForm.find('[id^="subject_"]').each(function () {
                        var id = $(this).attr("id").split("subject_")[1];
                        var subject = form.find('#subject_'+id).val();
                        if (subject == subj_data){
                            var version = form.find('#version_'+id).val();
                            if (version){
                                arr.push(version);
                            }
                        }
                    });
                    return arr;
                },
                changeVersion: function (id) {
                    var subject = form.find('#subject_'+id).val();
                    var version = form.find('#version_'+id).val();
                    $this.funObj().addGrade(id, subject, version);
                },
                addAction : function () {
                    var dom = $($this.demo.clone());
                    $('.SubVerTr:last').after(dom);
                    // var index = $('.SubVerTr').length - 1 ;
                    var index = 0;
                    $this.addAreaGroupForm.find('[id^="trId_"]').each(function () {
                        var id = $(this).attr("id").split("trId_")[1];
                        if (index < parseInt(id)){
                            index = parseInt(id);
                        }
                    });
                    index++;
                    dom.find('[name="data[0][subjectId]"]').attr('name','white['+index+'][subjectId]').attr('id','subject_'+index);
                    dom.find('[name="data[0][versionId]"]').attr('name','white['+index+'][versionId]').attr('id','version_'+index);
                    dom.find('[id="grade_0"]').attr('id','grade_'+index);
                    dom.find('[id="delTdLine_0"]').attr('id','delTdLine_'+index);
                    dom.find('[id="delLine_0"]').attr('id','delLine_'+index);
                    dom.attr('id','trId_'+index);
                    document.getElementById('delTdLine_'+index).style.display = 'table-cell';
                    $('#subject_'+index).select2({placeholder: '数据加载中..'});
                    $('#version_'+index).select2({placeholder: '数据加载中..'});
                    xhExtra.ajaxRequest('res/getSubjectByStage', {stage: stageId}, {check:true}, function (data) {
                        $('#subject_'+index).select2({placeholder: '请选择学科', data: data, allowClear: true});
                        $('#version_'+index).select2({placeholder: '请选择版本'});
                    });
                },
                addGrade: function (id, subject, version) {
                    form.find('#grade_'+id).html('');
                    if (version !== null && version !== '' && version !== undefined){
                        xhExtra.ajaxRequest('res/getGradeBySubVer', {subject: subject, version: version,stage:stageId}, {check:true, async:false}, function (data) {
                            if (data !== '' ){
                                str = '';
                                $.each(data, function (value, name) {
                                    str += '<label id="singleGradeLab_'+id+'_'+value+'" style="width: fit-content;padding-right: 5px">' +
                                        '<input type="checkbox" name="white['+id+'][grade][]" checked="checked" value="' + value + '">'+ name +
                                        '</label>';
                                    str += '<a id="singleGradeA_'+id+'_'+value+'" style="margin-right: 5px;cursor: pointer;color: red;padding-right: 5px">×</a>';
                                });
                            } else {
                                str = '<span style="color: grey;font-size:12px;">暂无数据</span>';
                            }
                            form.find('#grade_'+id).append($(str));
                        });
                    }
                },
                saveAction: function () {
                    $this.addAreaGroupForm.find('[id^="subject_"]').each(function () {
                        if ($(this).hasClass("needDisable")){
                            $(this).prop('disabled',false)
                        }
                    });
                    $this.addAreaGroupForm.find('[id^="version_"]').each(function () {
                        if ($(this).hasClass("needDisable")){
                            $(this).prop('disabled',false)
                        }
                    });
                    var notChecked = $("input:checkbox").not("input:checked");
                    var blackArr = [];
                    if (notChecked.length !== 0) {
                        notChecked.each(function(i){ //未被选中的记为黑名单
                            var index = $(this).parent().parent().attr('id').split("_")[1];
                            var sub = $('#subject_'+index).val();
                            var ver = $('#version_'+index).val();
                            var params = {
                                subject : sub,
                                version : ver,
                                grade : $(this).val()
                            };
                            blackArr.push(params);
                        });
                    }
                    $this.form.submit('res/saveWhiteAndBlackData',{schoolId:schoolId, blackArr: blackArr},function (res) {
                        location.reload();
                    },{check:true,success:true});
                    $this.addAreaGroupForm.find('[id^="subject_"]').each(function () {
                        if ($(this).hasClass("needDisable")){
                            $(this).prop('disabled',true)
                        }
                    });
                    $this.addAreaGroupForm.find('[id^="version_"]').each(function () {
                        if ($(this).hasClass("needDisable")){
                            $(this).prop('disabled',true)
                        }
                    });
                }
            }
        }
    }
};
